import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'

// 无需token直接放行白名单
const writeList = ['/404', '/login']

router.beforeEach(async (to, from, next) => {
  const token = store.getters.token
  NProgress.start()
  // 判断是否存在 token , 存在执行
  if (token) {
    const userInfo = store.getters.userInfo
    if (!userInfo.userId) {
      const { roles } = await store.dispatch('user/getUserInfo')
      const routes = await store.dispatch('permission/setRoute', roles.menus)
      console.log(routes)
      router.addRoutes([
        ...routes,
        { path: '*', redirect: '/404', hidden: true }
      ])
      return next(to.path)
    }
    if (to.path === '/login') {
      NProgress.done()
      Message({
        message: '系统检查到你已登陆',
        type: 'success'
      })
      return next('/')
    }

    return next()
  }

  // token  不存在执行

  if (writeList.includes(to.path)) {
    return next()
  }

  next('/login')
  Message({
    message: '系统检查到你未登陆',
    type: 'error'
  })
})

router.afterEach((to, form) => {
  NProgress.done()
})
